package com.example.teaculture.DB;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.teaculture.tools.Favor;

import java.util.ArrayList;
import java.util.List;

public class FavorDao {
    DBOpenHelper helper;
    SQLiteDatabase sqLiteDatabase;
    public FavorDao(Context context){
        helper=new DBOpenHelper(context);   //与数据库建立连接
    }
    //插入数据
    public void insertDetsilNews(Favor favor){
        SQLiteDatabase db=helper.getWritableDatabase();
        db.execSQL("insert into favor(_title,_url)" +  //将要收藏新闻的标题title，标识docid，详细地址url传入数据库，便可以依此打开新闻详显
                "values(?,?)",new String[]{favor.getTitle(),favor.getUrl()});
        db.close();
    }
    //删除数据
    public void del(String docid){   //根据传入参数docid删除数据
        SQLiteDatabase db=helper.getReadableDatabase();
        db.execSQL("delete from favor where _docid = ?",new Object[]{docid});
        db.close();
    }

    //查询数据
    public List<Favor> findSelected(){
        SQLiteDatabase db=helper.getReadableDatabase();
        Cursor c=db.rawQuery("select * from favor", null);    //只有对数据进行查询时，才用rawQuery()，增、删、改和建表，都用execSQl()
        List<Favor> list=new ArrayList<Favor>();
        while(c.moveToNext()){
            Favor favor=new Favor();
            favor.setTitle(c.getString(c.getColumnIndex("_title")));
            favor.setUrl(c.getString(c.getColumnIndex("_url")));
            favor.setDocid(c.getString(c.getColumnIndex("_docid")));
            list.add(favor);
        }
        c.close();
        db.close();
        return list;
    }
}
